// 定义弹球计数变量
const para = document.querySelector('p');
let count = 0;

// 设置画布
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

/*
浏览器窗口的视口（viewport）高/宽度（以像素为单位）；
如果有滚动条，也包括滚动条高/宽度。
*/
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;

// 生成随机数的函数
function random(min, max) {
  const num = Math.floor(Math.random() * (max - min)) + min;
  return num;
}

// 生成随机的颜色
function randomColor() {
  return 'rgb(' + random(0, 255) + ',' +
    random(0, 255) + ',' +
    random(0, 255) + ')'
}

// Shape 构造器
function Shape(x, y, velX, velY, exists) {
  this.x = x;
  this.y = y;
  this.velX = velX;
  this.velY = velY;
  this.exists = exists;
}
// 定义 Ball 构造器，继承自 Shape
function Ball(x, y, velX, velY, exists, color, size) {
  // 继承Shape
  Shape.call(this, x, y, velX, velY, exists)
  this.color = color;
  this.size = size;
}

Ball.prototype = Object.create(Shape.prototype)
Ball.prototype.constructor = Ball;

// 画出小球的方法
Ball.prototype.draw = function () {
  // 声明我们现在要开始在纸上画一个图形了
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
  ctx.fill()
}

// 更新小球的位置
Ball.prototype.update = function () {
  if ((this.x - this.size) <= 0 || (this.x + this.size) >= width) {
    this.velX = -this.velX
  }
  if ((this.y - this.size) <= 0 || (this.y + this.size) >= height) {
    this.velY = -this.velY
  }
  this.x += this.velX
  this.y += this.velY

}

// 添加碰撞检测
Ball.prototype.collisionDetect = function () {
  // 遍历 balls[] 数组中的小球。
  for (let j = 0; j < balls.length; j++) {
    // if语句判断调用方法的小球是否为当前遍历的小球 
    if (this !== balls[j]) {
      // distance为两个小球中心的距离
      const dx = this.x - balls[j].x;
      const dy = this.y - balls[j].y;
      // 开平方根
      const distance = Math.sqrt(dx * dx + dy * dy);

      // 两个小球中心的距离小于两小球的半径和则说明两小球相撞
      if (distance < this.size + balls[j].size) {
        // 将两个小球的颜色都设置成随机的一种
        balls[j].color = this.color = randomColor();
      }
    }
  }
}

// 定义操作的球
function EvilCircle(x, y, exists) {
  Shape.call(this, x, y, 20, 20, exists)
  // 定义自己的一些属性
  this.color = 'white';
  this.size = 10;
}
// Object.create()方法创建一个新对象，使用现有的对象来提供新创建的对象的__proto__
// EvilCircle的prototype指向它继承的构造函数的__proto__
EvilCircle.prototype = Object.create(Shape.prototype)
// 原型对象的constructor又指向该原型象
EvilCircle.prototype.constructor = EvilCircle.prototype

// 定义 EvilCircle 绘制方法
EvilCircle.prototype.draw = function () {
  ctx.beginPath();
  // 边框的颜色
  ctx.strokeStyle = this.color;
  ctx.lineWidth = 3;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  // 描边
  ctx.stroke();
}

// 定义 EvilCircle 的边缘检测（checkBounds）方法
EvilCircle.prototype.checkBounds = function () {
  if ((this.x + this.size) >= width) {
    this.x -= this.size;
  }

  if ((this.x - this.size) <= 0) {
    this.x += this.size;
  }

  if ((this.y + this.size) >= height) {
    this.y -= this.size;
  }

  if ((this.y - this.size) <= 0) {
    this.y += this.size;
  }
};

// 定义 EvilCircle 控制设置（setControls）方法
EvilCircle.prototype.setControls = function () {
  window.onkeydown = e => {
    switch (e.key) {
      case 'a':
      case 'A':
      case 'ArrowLeft':
        console.log(this);
        this.x -= this.velX;
        break;
      case 'd':
      case 'D':
      case 'ArrowRight':
        this.x += this.velX;
        break;
      case 'w':
      case 'W':
      case 'ArrowUp':
        this.y -= this.velY;
        break;
      case 's':
      case 'S':
      case 'ArrowDown':
        this.y += this.velY;
        break;
    }
  }
}

// 定义 EvilCircle 冲突检测函数
EvilCircle.prototype.collisionDetect = function () {
  for (let i = 0; i < balls.length; i++) {
    if (balls[i].exists) {
      const dx = this.x - balls[i].x
      const dy = this.y - balls[i].y
      const distance = Math.sqrt(dx * dx + dy * dy)

      if (distance <= this.size + balls[i].size) {
        balls[i].exists = false
        balls.splice(i, 1)
        this.size += 2
        count--
        console.log(balls.length);
        para.textContent = "剩余彩球数：" + count
      }
    }
  }
}

// 存储小球
let balls = [];
while (balls.length < 25) {
  let size = random(10, 20)
  let ball = new Ball(
    // 球至少离画布边缘球本身一倍宽度的距离
    random(0 + size, width - size),
    random(0 + size, height - size),
    random(-7, 7),
    random(-7, 7),
    true,
    randomColor(),
    size,
  )
  balls.push(ball)
  count++
  para.textContent = "剩余彩球数：" + count
}

// 定义一个循环来不停地播放
let evil = new EvilCircle(random(0, width), random(0, height), true)
evil.setControls()

function loop() {
  // 填充的颜色设置成半透明的rgba(0,0,0,0.25)
  // 也就是让之前的视图留下来一点点
  // 从而可以看到小球运动时的轨迹
  ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
  ctx.fillRect(0, 0, width, height);

  for (let i = 0; i < balls.length; i++) {
    balls[i].draw();
    balls[i].update();
    // 检测小球碰撞
    balls[i].collisionDetect();
  }
  evil.draw();
  evil.checkBounds();
  evil.collisionDetect()

  // requestAnimationFrame() 方法再运行一次函数 递归
  requestAnimationFrame(loop);

}
loop();
